Tanstack Routerでfile-based routing
code:_
src/
├── routes/ ← route 定義
│ ├── __root.tsx ← routeのRoot(createRootRoute)
│ │ <Outlet />で子ルートをレンダリング
│ │ 共通の <Link> やナビゲーション
│ │
│ ├── index.tsx ← "/" に対応(createFileRoute("/"))
│ └── about.tsx ← "/about" に対応(createFileRoute("/about"))
│
├── main.tsx ← エントリーポイント
│ routeTree.gen.ts を import
│ createRouter({ routeTree }) でルーター作成
│ <RouterProvider router={router} />
│
├── 📄 routeTree.gen.ts ← tsrで自動生成される
ファイル構造に基づいてルートツリーを構築
src/routes/__root.tsx
code:ts
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ params }) => fetchPost(params.postId),
component: PostPage,
errorComponent: ErrorComponent,
pendingComponent: LoadingComponent,
})
file basedだけど'/posts/$postId'は自分で指定するんやmrsekut.icon
自動で型推論されるので params.postId は型安全
エントリポイント
ルーターインスタンスの作成
bun run devして起動し続けてると
src/routes/内にtsファイルを作ると、自動でrouteの雛形が作られて体験が良い